<?php
global $AppUI, $m, $tab;

if (isset($_GET['tab'])) {
	$AppUI->setState('QuotationsIdxTab', $_GET['tab']);		// saves the current tab box state
}
$tab = $AppUI->getState('QuotationsIdxTab') !== NULL ? $AppUI->getState('QuotationsIdxTab') : 0;
$active = intval(!$AppUI->getState('QuotationsIdxTab'));

// Get login object
$uid = $AppUI->user_id;

// setup the title block with Name, Icon and Help
$titleBlock = new CTitleBlock('Quotations', 'quotations.jpg', $m, "$m.$a");
$titleBlock->addCell();

$titleBlock->addCell(
	'<input type="submit" class="button" value="'.$AppUI->_('quotation list').'">', '',
	'<form action="?m=quotations" method="post">', '</form>'
);

//finally show the titleBlock
$titleBlock->show();

// retrieve GET-Parameters via dPframework
$quote_id = intval(dPgetParam($_GET, "quote_id", 0));

// TODO: Check permission role
$perms =& $AppUI->acl();
// Check edit
$denyEdit = !$perms->checkModuleItem($m, 'edit', $quote_id);
// Check create
$denyAdd = !$perms->checkModule($m, 'add');

if($denyEdit and (0 < $quote_id)) {
	$AppUI->setMsg('Edit Permission Deny', UI_MSG_ERROR);
	$AppUI->redirect(PUBLIC_PAGE);
}
if($denyAdd){
	$AppUI->setMsg('Add Permission Deny', UI_MSG_ERROR);
	$AppUI->redirect(PUBLIC_PAGE);
}
require_once($AppUI->getModuleClass('companies'));
require_once($AppUI->getModuleClass('suppliers'));
require_once($AppUI->getMasterDataClass('mdtype'));
require_once($AppUI->getMasterDataClass('mdstatus'));
require_once($AppUI->getMasterDataClass('mdcurrency'));

//
$obj = new CQuotations();
// load the record data in case of that this script is used to
// edit the quote qith quotation_id(transmitted via GET)
if($quote_id > 0 and !$obj->load($quote_id, false)) {
	//$AppUI->setMsg('Quotations');
	//$AppUI->setMsg("invalidID", UI_MSG_ERROR, true);
	//$AppUI->redirect();
	//go back to the calling location
}

$msg = '';
// $canDelete = $obj->canDelete($msg, $quote_id);

// setup the title block
$ttl = $quote_id > 0 ? "Edit Quote" : "New Quote";
$titleBlock = new CTitleBlock($ttl, 'quotations.jpg', $m, "$m.$a");
// also have a breadcrumb here

//if($denyEdit) {
$pathQuoteList = './index.php?m=quotations&tab=0';
if(0 < $quote_id) {
	$obj->load($quote_id);
	$row = $obj;
}

$supplierList = getSupplierList();
$supplierList = arrayMerge(array(''=>"" . $AppUI->_(''). ""), $supplierList);

// Load Object Status
$objMD = new CMdStatus();
$statList = $objMD->getStatusList('Quotation');
// Remove active and complete when Create Quotation or Line List == 0
// Get id of active, complete
$active_key = dPgetSysVal(ACTIVE_KEY);
$objMD->loadByCode($active_key['code']);
$actStatusId = $objMD->status_id;

$comp_key = dPgetSysVal(COMPLETED_KEY);
$objMD->loadByCode($comp_key['code']);
$compStatusId = $objMD->status_id;

if($quote_id > 0){
	// Check line list
	require_once('quotation_lines.class.php');
	$line_obj = new CQuotation_lines();
	$line_list = $line_obj->getListByQuoteId($uid, $quote_id);
	if((is_null($line_list)) or (!is_array($line_list)) or (sizeof($line_list) == 0)){
		unset($statList[$actStatusId]);
		unset($statList[$compStatusId]);
	}
}
else{
	// Remove active_key and completed key
	unset($statList[$actStatusId]);
	unset($statList[$compStatusId]);

	// set value default for create quotation
	// TODO: recalucate default value for statList, I should hard code index 1 is value default
	if(is_array($statList) and (1 < count($statList))){
		$row = new stdClass();
		$tmp = '';
		// Don't use $statList[1]
		foreach($statList as $key => $value){
			if($key){
				$tmp = $key;
				break;
			}
		}
		$row->quote_status = $tmp;
	}
}

$objMD = new CMdType();
$typeList = $objMD->getTypeList('Quotation');
$typeList = arrayMerge(array(''=>''), $typeList);

$shipTypeList = $objMD->getTypeList('ShippingType');
$shipTypeList = arrayMerge(array(''=>''), $shipTypeList);

$objMD = new CCompany();
$cusList = $objMD->getAllowedRecords($AppUI->user_id, 'company_id, company_name', 'company_name');
$cusList = arrayMerge(array(''=>''), $cusList);

// Curency list
$objMD = new CMdCurrency();
$curList = $objMD->getCurrencyList();
$curList = arrayMerge(array(''=>''), $curList);
$view = '';

$q = new DBQuery();
$q->addTable('quotations');
$q->addQuery('quote_code');
if (isset($row->quote_id)) {
	$q->addWhere("quote_id != $row->quote_id");
}

$quoteCodeList = $q->loadColumn();
$qCL = '["' . implode('", "', $quoteCodeList) . '"]';

?>
<form name="editFrm" action="./index.php?m=quotations" method="post">
<input type="hidden" name="dosql" value="do_quote_crud" />
<input type="hidden" name="del" value="0" />
<input type="hidden" name="quote_id" value="<?=$quote_id?>" />
<input type="hidden" name="quote_version" value="<?=@$row->quote_version?>" />
<table cellspacing="0" cellpadding="4" border="0" width="100%" class="infopanel">
<tr>
	<td>
		<input class="button" type="submit" name="saveAction" value="<?=$AppUI->_('save');?>"/>
		<input class="button" type="button" name="cancelAction" value="<?=$AppUI->_('cancel');?>" onclick="return doCancel('<?=$pathQuoteList?>');"/>
	</td>
</tr>
</table>
<table cellspacing="0" cellpadding="4" border="0" width="100%" class="subinfopanel">
<tr>
	<td align="right"> * <?=$AppUI->_('Code')?></td>
	<td>
		<input type="text" class="text" name="quote_code" id="quote_code" style="width: 200px;" value="<?=@$row->quote_code?>" autocomplete="off" title="Hint :: Quotation code is required and not duplicated"/>
	</td>
	<td nowrap="nowrap" align="right">
		 * <?=$AppUI->_('Customer')?>
	</td>
	<td style='width: 70%;'>
		<?= arraySelect($cusList, 'quote_customer', ' id="quote_customer" size="1" class="text" style="width: 300px;" ', @$row->quote_customer, true)?>
	</td>
</tr>
<tr>
	<td align="right">
		 * <?=$AppUI->_('Name')?>
	</td>
	<td>
		<input type="text" class="text" name="quote_name" id="quote_name" value="<?=@$row->quote_name?>" style="width: 200px;" autocomplete="off" <?=$view?> title="Hint :: Quotation name is required"/>
	</td>
	<td align="right">
		<?=$AppUI->_('Supplier')?>
	</td>
	<td>
		<?= arraySelect($supplierList, 'quote_supplier', ' id="quote_supplier" size="1" class="text" style="width: 300px;"', @$row->quote_supplier, true)?>
	</td>
</tr>
<tr>
	<td align="right">
		 * <?=$AppUI->_('Status')?>
	</td>
	<td>
		<?= arraySelect($statList, 'quote_status', ' id="quote_status" size="1" class="text" style="width: 200px;" ', @$row->quote_status, true)?>
	</td>
	<td align="right">
		 * <?=$AppUI->_('Type')?>
	</td>
	<td>
		<?= arraySelect($typeList, 'quote_type', ' id="quote_type" size="1" class="text" style="width: 300px;" ', @$row->quote_type, true)?>
	</td>
</tr>
<tr>
	<td nowrap="nowrap" align="right">
		 * <?=$AppUI->_('Shipping Type')?>
	</td>
	<td>
		<?= arraySelect($shipTypeList, 'quote_shipping_type', ' id="quote_shipping_type" size="1" class="text" style="width: 200px;" ', @$row->quote_shipping_type, true)?>
	</td>
	<td nowrap="nowrap" align="right">
		 * <?=$AppUI->_('Currency')?>
	</td>
	<td>
		<?= arraySelect($curList, 'quote_currency', ' id="quote_currency" size="1" class="text" style="width: 200px;"', @$row->quote_currency, true)?>
	</td>
</tr>
<tr>
	<td align="right">
		<?=$AppUI->_('Remarks')?>
	</td>
	<td colspan="3">
		<textarea class="text" id="quote_remarks" name="quote_remarks" rows="3" cols="80" style="width: 590px;" title="Hint :: Remarks should be longer than 115 characters"><?=@$row->quote_remarks?></textarea>
	</td>
</tr>
</table>
</form>

<div id="validation_rules" style="visibility: hidden; display: none">
	var fQuoteCode = new LiveValidation('quote_code', {onlyOnBlur: true});
	fQuoteCode.add( Validate.Presence);
	fQuoteCode.add( Validate.Exclusion , {within: <?=$qCL?>});

	fQuoteCode.add( Validate.Length, {minimum: 1, maximum: 50});

	var fquoteCustomer = new LiveValidation('quote_customer');
	fquoteCustomer.add( Validate.Presence);

	var fquoteCustomerId = new LiveValidation('quote_customer');
	fquoteCustomerId.add( Validate.Numericality, {minimum: 1, maximum: 999999});

	var fQuoteName = new LiveValidation('quote_name');
	fQuoteName.add( Validate.Presence);
	fQuoteName.add( Validate.Length, {minimum: 1, maximum: 256});

	var fQuoteStatus = new LiveValidation('quote_status');
	fQuoteStatus.add( Validate.Presence);
	fQuoteStatus.add( Validate.Length, {minimum: 1, maximum: 9});

	var fQuoteType = new LiveValidation('quote_type');
	fQuoteType.add( Validate.Presence);
	fQuoteType.add( Validate.Numericality, {minimum: 1, maximum: 999999});

	var fQuoteShippingType = new LiveValidation('quote_shipping_type');
	fQuoteShippingType.add( Validate.Presence);
	fQuoteShippingType.add( Validate.Length, {minimum: 1, maximum: 9});

	var fQuoteRemarks = new LiveValidation('quote_remarks');
	fQuoteRemarks.add( Validate.Length, {maximum: 255} );

	// Comment block code because Live validation is fired event onchange
	//var fQuoteCurrency = new LiveValidation('quote_currency');
	//fQuoteCurrency.add( Validate.Presence);
	//fQuoteCurrency.add( Validate.Numericality, {minimum: 1, maximum: 999999});

</div>
<script language="JavaScript" type="text/javascript">
	eval($('validation_rules').innerHTML);
</script>